import { Message } from "element-ui";
import {
  queryCommonStationUnitsInfo,
  addConventionalUnit,
  downloadInfoSpecifiedInfo,
} from "@/api/conventionalUnit.js";
import { getPdf } from "@/api/windPower.js";
import {
  regulationOrgList,
  stationTypeLists,
  adjustRegulationList,
  voltageLevelList,
  queryStationNameList
} from "@/api/dict.js";
//引入VueOfficePdf组件
import * as XLSX from "xlsx";
import { exportFn } from "@/utils/exportTable.js";
export default {
  name: "conventionalUnit",
  data() {
    let yesOrNoList = {
      0: "否",
      1: "是",
    };
    const isResponseFilter = (row, column) => {
      return yesOrNoList[row.isResponse];
    };
    return {
      // 上调下调是否投入字典
      adjustRegulationList: [],
      voltageLevelLists: [], //电压等级下拉框的数据
      isYes: [
        {
          label: "是",
          value: "1",
        },
        {
          label: "否",
          value: "0",
        },
      ],
      formData: new FormData(), //载体
      queryCommonStationUnitsInfo,
      queryStationNameList,
      pdf: "", //设置文档地址
      getFrom: {
        companyId: "",
      }, //每行的数据
      addDialogVisibleTitle: "新增",
      queryDetailDialog: {
        regulationOrgId: "",
        voltageLevelCode: "",
        stationName: "",
        ownersName: "",

        isProduction: null,
        capStart: "",
        capEnd: "",
        productionTime: "",
        isRegulation: null,
        adjustRegulationCode: "",
        isResponse: null,
        // stationType: '7',
      },
      queryDetailParam: {
        regulationOrgId: "",
        voltageLevelCode: "",
        stationName: "",
        ownersName: "",

        isProduction: null,
        capStart: "",
        capEnd: "",
        productionTime: "",
        isRegulation: null,
        adjustRegulationCode: "",
        isResponse: null,
        powerStart: "",
        powerEnd: "",
        speedStart: "",
        speedEnd: "",
        powerDurationStart:'',
        powerDurationEnd:'',
        // stationType: '7',
      },
      queryParam1: { regulationOrgId: '' },

      tableData: [], //每页的表格数据,
      operate: "add",
      id: 0,
      dispatchList: [], //调度
      stationTypeLists: [], //类型
      // 预览弹框
      dialogPreVisible: false,
      headList: [
        {
          name: "所属调管调度机构",
          value: "regulationOrgName",
          noSort: true,
        },
        { name: "场站名称", value: "stationName", noSort: true },
        { name: "控制单元", value: "unitsName", noSort: true },
        { name: "升压站接入电压等级", value: "voltageLevelCode", noSort: true },
        {
          name: "上调/下调是否投入",
          value: "adjustRegulationCode",
          noSort: true,
        },
        {
          name: "是否具备惯量响应",
          value: "isResponse",
          noSort: true,
          formatter: isResponseFilter,
        },
        { name: "频率响应死区", value: "deadZone", noSort: true },
        { name: "调差系数", value: "adjustRatio", noSort: true },
        { name: "启动功率门槛", value: "startingPowerThreshold", noSort: true },
        { name: "下调限幅", value: "lowerLimit", noSort: true },
        { name: "上调限幅", value: "upLimit", noSort: true },
      ],
      rules: {
        stationName: [
          { required: true, message: "请选择场站名称", trigger: "change" },
        ],
        ownersName: [
          { required: true, message: "请选择产权单位", trigger: "change" },
        ],
      },
      // 新增弹框显示
      dialogFormVisible: false,
      formLabelWidth: "120px",
    };
  },
  mounted() {
    // this.fetchData();
  },
  created() {
    this.regulationOrgList();
    this.stationTypeList();
    this.getAdjustRegulationList();
    this.voltageLevelList();

    this.queryParam1.regulationOrgId =  this.queryDetailParam.regulationOrgId
  },

  computed: {},
  methods: {
    inputChange(val) {
      console.log(val, '搜索下拉框val')
      this.queryDetailParam.stationName = this.$refs.stationRef.value
    },

    regulationOrgChange(val){
      this.queryParam1.regulationOrgId = val
      this.$refs.stationRef.getDataInit()
    },

    handleClear_1() {
      this.$set(this.queryDetailParam, 'stationName', '')
    },
    // 电压等级下拉框的数据
    async voltageLevelList() {
      await voltageLevelList().then((res) => {
        if (res.code === "000000") {
          this.voltageLevelLists = res.data;
        }
      });
    },
    // 获取上调/下调是否投入字典
    async getAdjustRegulationList() {
      const res = await adjustRegulationList();
      this.adjustRegulationList = res.data;
      // console.log(res);
    },
    // 新增弹框
    addWindPower() {
      this.id++;
      this.addDialogVisibleTitle = "新增";
      this.dialogFormVisible = true;
      (this.operate = "add"),
        (this.getFrom = { regulationOrgId: "1", stationType: "1" });
    },
    // 获取表格多行选中的数据
    getMultipleSelection() {
      this.tableData = JSON.parse(
        JSON.stringify(this.$refs.conventionalUnitTable.multipleSelection)
      );

      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },
    // 编辑
    editWindPower() {
      this.operate = "edit";
      this.getMultipleSelection();
      if (this.tableData && this.tableData.length < 1) {
        Message.warning("请先勾选要编辑的数据");
      } else if (this.tableData && this.tableData.length > 1) {
        Message.warning("编辑的时候只能选择一条数据,请重新选择");
        return false;
      } else {
        this.addDialogVisibleTitle = "编辑";
        this.queryDetailDialog =
          this.$refs.conventionalUnitTable.getMultipleSelection()[0];
        this.dialogFormVisible = true;
        return true;
      }
    },

    // 检索
    searchList() {
      this.$refs.conventionalUnitTable.getDataInit();
    },
    // 检索重置
    resetSearchList() {
      for (let key in this.queryDetailParam) {
        this.queryDetailParam[key] = "";
      }
      this.$refs.conventionalUnitTable.getDataInit();
    },

    // 详情重置
    resetCon() {
      // this.getFrom = {}
      // if (this.$refs.childRules.station) {
      //   this.$refs.childRules.$refs.station.labels = ''
      // }
      // if (this.$refs.childRules.$refs.company) {
      //   this.$refs.childRules.$refs.company.labels = ''
      // }
      this.queryDetailDialog = this.$options.data.queryDetailDialog;
    },

    // 保存
    saveForm() {
      this.$refs.childRules.validate((valid) => {
        if (!valid) return false;
        // 创建一个新的FormData对象
        const formData = new FormData();

        // 将this.queryDetailDialog中的属性添加到formData中
        for (let key in this.queryDetailDialog) {
          formData.append(key, this.queryDetailDialog[key]);
        }
        formData.append("operateCode", "2"); //
        addConventionalUnit(formData).then((res) => {
          //console.log(res, "wwwwwwwwwwwww");
          if (res.code === "000000") {
            this.dialogFormVisible = false;
            Message.success("编辑成功");
          }
          // if (res.code === '400001') {
          //   this.$confirm(res.mesg, '提示', {
          //     confirmButtonText: '确定',
          //     cancelButtonText: '取消',
          //     type: 'warning',
          //   }).then(()=>{
          //     this.dialogFormVisible = true           
          //   })
          // }
        });
      });

    },

    // 首先封装参数（对象）转换为formData格式
    getFormData(object) {
      let form = this.$refs.childRules;
      // 文件存在就append,不存在就不append,不往后台传递这个字段
      form.fileList1[0] &&
        this.formData.set("regulationReportForm", form.fileList1[0].raw);
      form.fileList2[0] &&
        this.formData.set("regulationTestPlan", form.fileList2[0].raw);
      form.fileList3[0] &&
        this.formData.set("regulationTestReport", form.fileList3[0].raw);
      // form.fileList4[0] &&
      //   this.formData.set("responsePlan", form.fileList4[0].raw);
      // form.fileList5[0] &&
      //   this.formData.set("responseReport", form.fileList5[0].raw);
      this.formData.set("unitsNumber", this.getFrom.unitsNumber);
      this.getFrom.regulationOrgId &&
        this.formData.set("regulationOrgId", this.getFrom.regulationOrgId);
      this.getFrom.stationType &&
        this.formData.set("stationType", this.getFrom.stationType);
      this.getFrom.singleMachineCap &&
        this.formData.set("singleMachineCap", this.getFrom.singleMachineCap);
      //台数存在就append,不存在就不append/set,不往后台传递字段
      this.getFrom.machineNum &&
        this.formData.set("machineNum", this.getFrom.machineNum);
      this.getFrom.unitsTotalCap &&
        this.formData.set("unitsTotalCap", this.getFrom.unitsTotalCap);

      // 区分编辑还是新增
      if (this.operate === "add" || this.operate === "copy") {
        this.formData.set("operateCode", "1");
      }
      if (this.operate === "edit") {
        this.formData.set("operateCode", "2");
        this.formData.set(
          "unitsId",
          this.$refs.conventionalUnitTable.multipleSelection[0].unitsId
        );
        this.formData.set(
          "regulationId",
          this.$refs.conventionalUnitTable.multipleSelection[0].regulationId
        );
      }

      return this.formData;
    },

    // 新增接口
    async addConventionalUnit() {
      // 在getFormData()方法里面写，取不到his.$refs.childRules.$refs.station值（因为异步，所以写在接口里）
      this.formData = this.getFormData();
      this.formData.set(
        "stationId",
        this.$refs.childRules.$refs.station.labels
      );
      //this.formData.set('stationName', this.$refs.childRules.$refs.station.stationName)
      // this.formData.set('companyName', this.$refs.childRules.$refs.company.labels)
      this.formData.set(
        "companyId",
        this.$refs.childRules.$refs.company.labels
      );
      await addConventionalUnit(this.formData).then((res) => {
        if (res.code === "000000") {
          Message.success(`${this.addDialogVisibleTitle}成功`);
          // 刷新列表的操作  getDataInit():组件的内置方法,用于刷新列表接口
          this.$refs.conventionalUnitTable.getDataInit();
          this.dialogFormVisible = false;
        }
      });
      // .catch((err) => {
      //   Message.error(`${this.addDialogVisibleTitle}失败`);
      // });
    },

    // 导出
    async downloadCon() {
      exportFn("定值单导出.xlsx", downloadInfoSpecifiedInfo, this.queryDetailParam);
    },

    //  导出
    exportExcel() {
      this.downloadCon();
    },

    // 总调下拉框的数据
    async regulationOrgList() {
      await regulationOrgList().then((res) => {
        if (res.code === "000000") {
          this.dispatchList = res.data;
        }
      });
    },

    // 场站类型下拉框的数据
    async stationTypeList() {
      await stationTypeLists().then((res) => {
        if (res.code === "000000") {
          this.stationTypeLists = res.data;
        }
      });
    },
    // 预览
    async doPreview(row, col) {
      const res = await getPdf(row[`${col}Id`]);
      if (
        res.fileType !== "pdf" &&
        res.fileType !== "xlsx" &&
        res.fileType !== "xls"
      ) {
        this.$message.warning("只支持pdf与excel格式的文件预览");
        return;
      }
      let typeList = {
        pdf: "application/pdf",
        xls: "application/vnd.ms-excel",
        xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      };
      const blob = new Blob([res], { type: typeList[res.fileType] });
      if (res.fileType === "pdf") {
        this.pdf = URL.createObjectURL(blob);
      } else {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = new Uint8Array(e.target.result);
          let workbook = XLSX.read(data, { type: "array" }); // 解析数据
          this.tableToHtml(workbook);
        };
        reader.readAsArrayBuffer(blob);
      }
      this.dialogPreVisible = true;
    },
    tableToHtml(workbook) {
      var worksheet = workbook.Sheets[workbook.SheetNames[0]];
      // var innerHTML = XLSX.utils.sheet_to_html(worksheet);
      if (document.querySelector("#tableHtml")) {
        document.querySelector("#tableHtml").innerHTML =
          XLSX.utils.sheet_to_html(worksheet);
        document.querySelector(".table-html-wrap table");
        let trs = document.querySelectorAll("tr");
        trs.forEach((tr) => {
          if (!tr.innerText.trim()) {
            tr.remove();
          }
        });
        document.querySelector(".el-dialog__body").style.overflowX = "auto";
      }
      let tds = document.querySelectorAll("td");
    },
    // 下载
    async doDownload(row, col, name) {
      let excelName = `${name}`;
      const res = await getPdf(row[`${col}Id`]);
      if (
        res.fileType !== "pdf" &&
        res.fileType !== "xlsx" &&
        res.fileType !== "xls"
      ) {
        this.$message.warning("只支持pdf与excel格式的文件下载");
        return;
      }
      let typeList = {
        pdf: "application/pdf",
        xls: "application/vnd.ms-excel",
        xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      };
      const link = document.createElement("a");
      let blob = new Blob([res], {
        type: typeList[res.fileType],
      });
      // xlsx的文件type

      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      link.download = excelName; //下载的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // async downloadWin() {
    //   let excelName = "导出常规机组列表.xlsx";
    //   const res = await downloadCommonStationWin(this.queryDetailParam);
    //   const link = document.createElement("a");
    //   let blob = new Blob([res], {
    //     type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    //   });
    //   link.style.display = "none";
    //   link.href = URL.createObjectURL(blob);
    //   link.download = excelName; //下载的文件名
    //   document.body.appendChild(link);
    //   link.click();
    //   document.body.removeChild(link);
    // },

    // 列表上传
    doUpload() {
      //
    },

    //列表查看，跳转到新型资源快速频率响应主动测试页面
    doCheck() {
      this.$router.push({ path: "/windPower", query: { stationId: "001" } });
      console.log(this.$route.path, "222");
      // this.$router.push({ name: 'home', params: { id: '001' } })
    },
  },
};
